package com.aj.databases.dao;

import java.sql.SQLException;
import java.util.List;

import android.content.Context;

import com.aj.databases.DatabaseHelper;
import com.aj.databases.entry.Home;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.RuntimeExceptionDao;

public class HomeDao {
	public RuntimeExceptionDao<Home, Integer> dao = null;
	private DatabaseHelper helper = null;

	public HomeDao(Context context) {
		helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
		dao = helper.getRuntimeExceptionDao(Home.class);
	}

	public Home getHome(Integer home_id) {
		try {
			List<Home> homeList = dao.queryBuilder().where()
					.eq(Home.ID, home_id).query();
			if (homeList != null && homeList.size() > 0) {
				return homeList.get(0);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Home getHomeOne() {
		try {
			List<Home> homeList = dao.queryBuilder().query();
			if (homeList != null && homeList.size() > 0) {
				return homeList.get(0);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Home insert(Home home) {
		try {
			List<Home> homeList = dao.queryBuilder().where()
					.eq(Home.FAMILY_ID, home.getFamilyId()).query();
			if (homeList != null && homeList.size() > 0) {
				home.setId(homeList.get(0).getId());
				dao.update(home);
				return home;
			} else {
				return dao.createIfNotExists(home);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}
